package com.mys.springboot.config.error;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

@ControllerAdvice
public class ControllerExceptionHandler {

	public static final String DEFAULT_ERROR_VIEW = "error/404";

	@ExceptionHandler(value = NoHandlerFoundException.class)
	public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception", e);
		mav.addObject("url", req.getRequestURL());
		mav.setViewName(DEFAULT_ERROR_VIEW);
		return mav;
	}
	
	/**
	 * 处理页面404
	 *
	 * @return
	 * @createdTime: 2016年12月2日 上午10:41:35
	 * @createdUser: mys
	 * @lastUpdatedTime:
	 * @lastUpdatedUser:
	 * @version: 1.0
	 * @param dispatcherServlet
	 * @return
	 */
	@Bean  
	public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
	    ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
	    dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
	    return registration;
	}
	
	/**
	 * 处理controller异常（除404以外）
	 *
	 * @return
	 * @createdTime: 2016年12月2日 上午10:48:41
	 * @createdUser: mys
	 * @lastUpdatedTime:
	 * @lastUpdatedUser:
	 * @version: 1.0
	 * @return
	 */
	@Bean
	public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
		SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
		simpleMappingExceptionResolver.setDefaultErrorView("error/500");
		return simpleMappingExceptionResolver;
	}
}